import React, { useState, useEffect, forwardRef } from 'react';
import { Table } from 'antd';
import styles from '../index.less';

import {
  FLOAT_MODULUS, // 浮点系数
  FLOAT_MODULUS_NUM, //浮点倍数
} from '../utils/constant';

const Footer = (props, parentRef) => {
  const { parentColumns, parentData, unitSize } = props;
  const [keys, setKeys] = useState([]);
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  // 同步横向滚动
  const scroll = () => {
    const tableBody = document.querySelectorAll('.ant-table-body');
    if (tableBody[1]) {
      tableBody[1].style.overflow = 'hidden';
      tableBody[0].onscroll = () => {
        tableBody[1].scrollLeft = tableBody[0].scrollLeft;
      };
    }
  };

  // 滚动 初始化 keys columns data
  useEffect(() => {
    scroll();
    const keyList = [];
    const columns = parentColumns.map((tar, index) => {
      if (index === 0) {
        return { ...tar, key: index };
      }
      keyList.push(tar.dataIndex);
      return {
        ...tar,
        key: `footer_${tar.key}`,
        render: text => <div className={Number(text) === 100 ? '' : 'colorRed'}>{text}%</div>,
      };
    });
    setKeys(keyList);
    setColumns(columns);
    const dataSource = createData(keyList);
    setData(dataSource);
  }, []);

  // 父级 parentData 变化的时候重新计算 data
  useEffect(() => {
    if (keys.length === 0) return;
    setData(createData(keys));
  }, [parentData]);

  // data计算
  const createData = keys => {
    const tableData = parentData.reduce((prev, curr, idx, arr0) => {
      const newObj = {};
      keys.map(tar => {
        const num1 = isNaN(Number(prev[tar])) ? 0 : Number(prev[tar]);
        const num2 = isNaN(Number(curr[tar])) ? 0 : Number(curr[tar]);
        newObj[tar] = (
          Number((num1 * FLOAT_MODULUS_NUM + num2 * FLOAT_MODULUS_NUM).toFixed(0)) /
          FLOAT_MODULUS_NUM
        ).toFixed(FLOAT_MODULUS);
      });
      return newObj;
    }, {});
    return [tableData];
  };

  return (
    <Table
      ref={parentRef}
      columns={columns}
      dataSource={data}
      style={{ paddingRight: 4 }}
      size="small"
      rowClassName={() => 'editable-row'}
      className={styles.footerTable}
      showHeader={false}
      pagination={false}
      scroll={{ x: parentColumns.length * unitSize + unitSize }}
    />
  );
};
const FooterRef = forwardRef(Footer);

export default FooterRef;
